<?php

namespace Auth\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\Adapter\DbTable;
use Zend\Session\Container as SessionContainer;
use Zend\View\Model\ViewModel;
use Auth\Form\LoginForm;

class LoginController extends AbstractActionController
{
    public function loginAction()
    {
        $form = new LoginForm();
        $loginMsg = array();
        $request = $this->getRequest();
        
        if($request->isPost()){
            //process
            $form->setData($request->getPost());
            if($form->isValid())
            {
                $dbAdaper = $this->serviceLocator->get('Zend\Db\Adapter\Adapter');
                $loginData = $form->getData(); 
                $authAdapter = new DbTable($dbAdaper , 'user' , 'username' , 'password' , 'MD5(?)');
                $authAdapter->setIdentity($loginData['username'])
                            ->setCredential($loginData['password']);
                $authService = $this->serviceLocator->get('auth_service');
                $authService->setAdapter($authAdapter);
                $result = $authService->authenticate();
                if($result->isValid()){
                    $userId = $authAdapter->getResultRowObject('id')->id;
                    $authService->getStorage()->write($userId);
                    return $this->redirect()->toUrl('/');
                }
                else{
                    $loginMsg = $result->getMessages();
                }
            }
        }        
        
        return new ViewModel(array(
            'title' => 'Login Form' ,
            'form'  => $form ,
            'loginMsg' => $loginMsg ,
        ));
    }
}

